// components/cart/cart.js
import tool from '../../modules/tool'
import store from '../../modules/store'

Component({
  /**
   * 组件的初始数据
   */
  data: {
    show: false,
    data: [],
    priceDisplay: 0,
    priceNum: 0,
    selected: 0,
    unselectable: [],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleSelectAll() {
      this.setData({
        selected: this.data.data.length,
        data: (() => {
          let t = this.data.data
          for (let i = 0; i < t.length; i++)t[i].selected = true
          return t
        })(),
      })
      this.computePrice()
    },
    handleUnselectAll() {
      this.setData({
        selected: 0,
        data: (() => {
          let t = this.data.data
          for (let i = 0; i < t.length; i++)delete t[i].selected
          return t
        })(),
      })
      this.computePrice()
    },
    async handleNext() {
      if (this.data.selected == 0) return
      let re = []
      for (let i = 0; i < this.data.data.length; i++) {
        if (this.data.data[i].selected) {
          let t = JSON.parse(JSON.stringify(this.data.data[i]))
          delete t.selected
          delete t.info
          t.cartId = this.data.data[i].id
          re.push(t)
        }
      }
      tool.handleShowPayPage(re)
    },

    computePrice() {
      let re = 0
      for (let i = 0; i < this.data.data.length; i++) {
        if (this.data.data[i].selected) {
          re += (() => {
            if (this.data.data[i].isPro) {
              return tool.getSinglePrice(this.data.data[i].info, this.data.data[i].options, this.data.data[i].num)
            } else {
              return this.data.data[i].info.price
            }
          })()
        }
      }
      this.setData({
        priceNum: re,
        priceDisplay: (re / 100).toString() + ((re / 100).toString().split('.')[1] ? ((re / 100).toString().split('.')[1].length == 1 ? '0' : '') : '')
      })
    },

    handleItemClick(e) {
      e = e.currentTarget.dataset
      if (!e.ispro) {
        wx.showActionSheet({
          itemList: ['查看活动信息', '查看表单'],
          success: (e) => {
            e = e.tapIndex
            if (e === 0) {
              tool.handleShowProductActivityDetailPage(e.ispro, e.iid)
            }
            if (e === 1) {
              // tool.handleShowActivityUserSubmitedForm(`我的表单`, )
            }
          }
        })
        return
      }
      tool.handleShowProductActivityDetailPage(e.ispro, e.iid)
    },

    addSelected(id) {
      id = id.currentTarget.dataset.iid
      let t = this.data.data
      for (let i = 0; i < t.length; i++) {
        if (t[i].id == id) {
          t[i].selected = true
        }
      }
      this.setData({
        data: t,
        selected: this.data.selected + 1
      })
      this.computePrice()
    },

    async deleteSelectCart() {
      tool.handleShowModel('是否删除选中项目？', true, async () => {
        let ids = []
        for (let i = 0; i < this.data.data.length; i++) {
          if (this.data.data[i].selected) ids.push(this.data.data[i].id)
        }
        let re = await tool.requestData('/cart/deleteByIds', {
          ids
        })
        if (re.status) {
          this.setData({
            selected: 0
          })
          await this.getData()
          this.computePrice()
          await tool.handleUpdateCartNum()
        } else {
          tool.handleShowToast(re.content, 'error')
        }
      })
    },

    deleteSelected(id) {
      id = id.currentTarget.dataset.iid
      let t = this.data.data
      for (let i = 0; i < t.length; i++) {
        if (t[i].id == id) {
          delete t[i].selected
        }
      }
      this.setData({
        data: t,
        selected: this.data.selected - 1
      })
      this.computePrice()
    },

    handleShowMenu(e) {
      let t = e.currentTarget.dataset
      e = e.currentTarget.dataset.iid
      let l = ['删除']
      if (!t.cannotSelect) {
        l.push('调整数量')
      }
      wx.showActionSheet({
        itemList: l,
        success: async (e1) => {
          switch (e1.tapIndex) {
            case 0:
              tool.handleShowModel('是否删除？', true, async () => {
                let re = await tool.requestData('/cart/delete', {
                  id: e
                })
                if (re.status) {
                  let selectedIds = []
                  for (let i = 0; i < this.data.data.length; i++) {
                    if (this.data.data[i].selected) selectedIds.push(this.data.data[i].id)
                  }
                  await this.getData()
                  await tool.handleUpdateCartNum()
                  let t = this.data.data
                  for (let i = 0; i < t.length; i++) {
                    if (selectedIds.indexOf(t[i].id) + 1) {
                      t[i].selected = true
                    }
                  }
                  this.setData({
                    data: t
                  })
                  this.computePrice()
                } else {
                  tool.handleShowToast(re.content, "error")
                }
              })
              break
            case 1:
              for (let i = 0; i < this.data.data.length; i++) {
                if (this.data.data[i].id == e) {
                  tool.controlInput('修改数量', '', 'number', this.data.data[i].num, async (value, done) => {
                    value = parseInt(value)
                    let re = await tool.requestData('/cart/changeNum', {
                      cartId: e,
                      num: value
                    })
                    if (re.status) {
                      done()
                      this.getData()
                    } else {
                      tool.handleShowToast(re.content, 'error')
                    }
                  }, (value) => {
                    value = parseFloat(value)
                    if (isNaN(value)) throw '数量应为正整数'
                    if (value != parseInt(value)) throw '数量应为正整数'
                    if (value < 1) throw '数量应为正整数'
                  })
                  break
                }
              }
              break
          }
        }
      })
    },

    async getData(first = false) {
      let re = await tool.requestData('/cart/getList', {
        openId: store.getItem('userData').openId
      }, 'get')
      if (re.status) {
        for (let i = 0; i < re.data.selectable.length; i++) {
          re.data.selectable[i].selected = true
        }
        this.setData({
          data: re.data.selectable,
          selected: re.data.selectable.length,
          unselectable: re.data.unselectable,
        })
        this.computePrice()
      } else {
        store.setItem('showCart')
        return
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
      await this.getData(true)
      this.setData({
        show: true
      })

      store.onChange('updateCartPage', () => {
        this.getData()
      })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    async onPullDownRefresh() {
      await this.getData()
      wx.stopPullDownRefresh()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
  },

  /**
   * 组件生命周期函数
   */
  lifetimes: {
    attached() {
      this.onLoad()
    }
  }
})